//
//  NetworkAPI.m
//  JingMai
//
//  Created by 戴怀诚 on 15/6/26.
//  Copyright (c) 2015年 戴怀诚. All rights reserved.
//

#import "NetworkAPI.h"

@implementation NetworkAPI

const NSString *serverAddress = @"http://121.40.58.75";

const NSString *kUrlKeyRegister = @"/api/register";


+ (NSURL*)urlWithKey:(const NSString*)key {
    return [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/", serverAddress, key]];
}

+ (id)sendSyncRequest:(ASIFormDataRequest*)request type:(NSString*)type stringEncode:(BOOL)encodeString options:(NSJSONReadingOptions)option
{
    [request setRequestMethod:type];
    [request startSynchronous];
    
    id response = nil;
    NSError *error = [request error];
    if (error == nil) { // NO error
        if (encodeString) {
            response = [NSJSONSerialization JSONObjectWithData:[[request responseString] dataUsingEncoding:NSUTF8StringEncoding] options:option error:nil];
        } else {
            response = [NSJSONSerialization JSONObjectWithData:[request responseData] options:option error:nil];
        }
    }
    
    return response;
}

+ (void)sendAsyncRequest:(ASIFormDataRequest*)request
                    type:(NSString*)type
          stringEncoding:(BOOL)stringEncoding
                 options:(NSJSONReadingOptions)option
              completion:(void (^)(id response, int statusCode))completion
{
    [request setRequestMethod:type];
    
    dispatch_queue_t serialQueue = dispatch_queue_create("com.jingmai.ASI.async", NULL);
    dispatch_async(serialQueue, ^{
        [request startSynchronous];
        id response = nil;
        int statusCode = 0;
        NSError *error = [request error];
        if (error == nil) {
            if (stringEncoding) {
                response = [NSJSONSerialization JSONObjectWithData:[[request responseString] dataUsingEncoding:NSUTF8StringEncoding] options:option error:nil];
            } else {
                response = [NSJSONSerialization JSONObjectWithData:[request responseData] options:option error:nil];
            }
            
            statusCode = [request responseStatusCode];
        }
        
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(response, statusCode);
            });
        }
    });
}

#pragma - API
+ (void)registerWithUsername:(NSString*)userName
                    password:(NSString*)password
                  completion:(void (^)(id response, int statusCode))completion
{
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[self urlWithKey:kUrlKeyRegister]];
    
    [request setPostValue:userName forKey:@"username"];
    [request setPostValue:password forKey:@"password"];
    
    [self sendAsyncRequest:request type:@"POST" stringEncoding:NO options:NSJSONReadingMutableLeaves completion:completion];
    
}










@end
